package cn.ac.iscas.service.transformer.dameng;

import cn.ac.iscas.domain.source.DamengSourceColumn;
import cn.ac.iscas.utils.DamengSqlUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.commons.collections4.CollectionUtils;

import java.util.*;

public class DamengDataDecompositionTransformer {
    private final static String ID = "data_decomposition";

    private final static String FRONT_TABLE_NAME = "srcTableName";
    private final static String TARGET_TABLE_NAME = "tgtTableName";
    private final static String FRONT_SCHEMA = "srcSchema";
    private final static String TARGET_SCHEMA = "tgtSchema";
    private final static String TARGET_COLUMN_NAME = "tgrColName";
    private final static String IS_CONSTANT_COLUMN = "isConstantCol";
    private final static String CONSTANT_VALUE = "constantVal";
    private final static String COLUMNS = "columns";
    private final static String LINES = "lines";

    private String jobId;
    private String componentId;
    private String frontTableName;
    private List<DamengSourceColumn> frontColumns;

    private String currentTableName;
    private List<DamengSourceColumn> currentColumns;

    public DamengDataDecompositionTransformer(String jobId, String taskId) {
        this.jobId = jobId;
        this.componentId = taskId;
    }

    public DamengDataDecompositionTransformer(String jobId, String taskId, String frontTableName, List<DamengSourceColumn> frontColumns) {
        this.jobId = jobId;
        this.componentId = taskId;
        this.frontTableName = frontTableName;
        this.frontColumns = frontColumns;
        this.currentColumns = frontColumns;
        this.currentTableName = String.format("\"%s\".\"%s_%s\"", jobId, ID, UUID.randomUUID().toString().substring(0, 6));
    }

    public DamengDataDecompositionTransformer() {

    }

    public List<String> getSql(Map<String, Object> parameterMap) {
        List<Map> parameters = (List<Map>) parameterMap.get("columns");
        List<String> sqls = new ArrayList<>();

        if (CollectionUtils.isEmpty(parameters)) {
            return null;
        }

        //多个数据源分别处理
        for (Map param : parameters) {
            String frontSchema = param.getOrDefault(FRONT_SCHEMA, "").toString();
            String targetSchema = param.getOrDefault(TARGET_SCHEMA, "").toString();
            String frontTableName = param.getOrDefault(FRONT_TABLE_NAME, "").toString();
            String targetTableName = param.getOrDefault(TARGET_TABLE_NAME, "").toString();

            String lines = param.getOrDefault(LINES, "").toString();
            //将字段数据转为List<Map>
            List<Map<String, String>> linesList = StringUtils.isNotBlank(lines) ? JSON.parseObject(lines, new TypeReference<List<Map<String, String>>>() {
            }) : null;
            List<String> selectTempTableSqlList = new ArrayList<>();
            List<String> targetColumnNames = new ArrayList<>();
            String targetTableNameWithSchema = "";
            if (Objects.nonNull(linesList)) {
                for (Map lineMap : linesList) {
                    String sourceColumns = lineMap.getOrDefault(COLUMNS, "").toString();
                    //将字段数据转为List<Map>
                    List<Map<String, String>> sourceColumnMap = StringUtils.isNotBlank(sourceColumns) ? JSON.parseObject(sourceColumns, new TypeReference<List<Map<String, String>>>() {
                    }) : null;
                    //获取目标数据表的字段
                    targetColumnNames = getTargetColumnNames(sourceColumnMap);
                    //拼接模式和数据表
                    String frontTableNameWithSchema = String.format("\"%s\".\"%s\"", frontSchema, frontTableName);
                    targetTableNameWithSchema = String.format("\"%s\".\"%s\"", targetSchema, targetTableName);
                    //获取查询sql
                    String selectTempTableSql = DamengSqlUtils.getSelectAndStaticSql(sourceColumnMap, frontTableNameWithSchema, targetTableNameWithSchema);
                    selectTempTableSqlList.add(selectTempTableSql);
                }
            }

            if (CollectionUtils.isNotEmpty(selectTempTableSqlList) && CollectionUtils.isNotEmpty(targetColumnNames)) {
                StringBuffer selectSqlBuffer = new StringBuffer();
                selectTempTableSqlList.forEach(sql -> {
                    selectSqlBuffer.append(sql);
                    selectSqlBuffer.append(" UNION ALL ");
                });
                selectSqlBuffer.deleteCharAt(selectSqlBuffer.length() - 1); // 删除末尾多余的UNION ALL
                String decompositionInsertSql = DamengSqlUtils.getDecompositionInsertSql(targetTableNameWithSchema, targetColumnNames, selectSqlBuffer.toString());
                sqls.add(decompositionInsertSql);

            }

        }

        return sqls;
    }

    private List<String> getTargetColumnNames(List<Map<String, String>> sourceColumnMap) {
        List<String> targetColumnNames = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(sourceColumnMap)) {
            for (Map<String, String> map : sourceColumnMap) {
                if (map.containsKey(TARGET_COLUMN_NAME) && isTargetColumnValid(map)) {
                    targetColumnNames.add(map.get(TARGET_COLUMN_NAME));
                }
            }
        }
        return targetColumnNames;
    }

    private boolean isTargetColumnValid(Map<String, String> map) {
        // 当静态数据为null时跳过该列
        return !(map.get(IS_CONSTANT_COLUMN).equals("true") && map.get(CONSTANT_VALUE) == null && !"来源表".equals(map.get(TARGET_COLUMN_NAME)));
    }

}
